package com.klikmee.sms.core.base.communicator.mtel;

import java.text.MessageFormat;
import java.util.Map;

import org.apache.log4j.Logger;

import com.klikmee.sms.core.base.CoreCacheDriver;
import com.klikmee.sms.core.base.communicator.DeliveryReport;
import com.klikmee.sms.core.model.OutgoingMessage;

/**
 * Cache driver impl for Mtel provider.
 * @author makcro
 *
 */
public class MtelCacheDriverImpl implements CoreCacheDriver<DeliveryReport, OutgoingMessage> {

	/**
	 * Logger instance
	 */
	private Logger logger = Logger.getLogger(MtelCacheDriverImpl.class);
	
	/**
	 * Instance of outgoing message cache. Read/write operations are performed on this instance
	 */
	private Map<String, OutgoingMessage> outgoingCache;
	
	/**
	 * Writes {@link OutgoingMessage} to cache.
	 * As the key {@link OutgoingMessage#getProvidersMesssageId()} is used
	 * Because Mtel resolves delivery report by this value. 
	 */
	@Override
	public void write(OutgoingMessage object) {
		// preapre the key
		String providersMesssageId = object.getProvidersMesssageId();
		outgoingCache.put(providersMesssageId, object);
		
		logger.info(MessageFormat.format("OutgoingMessage [{0}] written to cache", object.getId()));
	}

	/**
	 * Reads outgoing messages from cache using a delivery report info
	 */
	@Override
	public OutgoingMessage read(DeliveryReport key) {
		OutgoingMessage outgoingMessage = outgoingCache.get(key.getProvidersMessageId());
		if(outgoingMessage != null){
			logger.debug(MessageFormat.format("Outgoing message with providers id [{0}] read from cache", outgoingMessage.getProvidersMesssageId()));
		}
		return outgoingMessage;
	}
	
	/**
	 * Removes outgoing message from cache
	 */
	@Override
	public void remove(OutgoingMessage object) {
		OutgoingMessage outgoingMessage = outgoingCache.remove(object.getProvidersMesssageId());
		logger.debug(MessageFormat.format("Outgoing message with providers id [{0}] removed from cache", outgoingMessage.getProvidersMesssageId()));
	}
	
	public Map<String, OutgoingMessage> getOutgoingCache() {
		return outgoingCache;
	}
	
	public void setOutgoingCache(Map<String, OutgoingMessage> outgoingCache) {
		this.outgoingCache = outgoingCache;
	}
}
